package com.mystudy.netty.http.https;

import com.mystudy.netty.http.https.ssl.SSLContextFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.File;

/**
 * @program: infoalgorithm
 * @description: 服务端初始化类
 * @author: zhouzhilong
 * @create: 2019-10-25 17:13
 **/
public class HttpPipelineInitializer extends ChannelInitializer<Channel> {
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpPipelineInitializer.class);
    @Override
    protected void initChannel(Channel ch) throws Exception {
        String jksPath = System.getProperty("user.dir") + "/httpserver.jks";
        LOGGER.debug("jksPath = [{}]",jksPath);
        LOGGER.debug("jks exist = [{}]",new File(jksPath).exists());

        SSLContext sslContext = SSLContextFactory.getServerContext(jksPath,"wizarpos","wizarpos");
        //设置为服务器模式
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        //是否需要验证客户端 。 如果是双向认证，则需要将其设置为true，同时将client证书添加到server的信任列表中
        sslEngine.setNeedClientAuth(false);

        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("ssl",new SslHandler(sslEngine));
        //http的编解码器
        pipeline.addLast("codec",new HttpServerCodec());
        //一个请求最大只允许512kb
        pipeline.addLast("aggregator",new HttpObjectAggregator(512*1024));
        //业务处理器
        pipeline.addLast(new HttpServerHandler());
    }
}
